package com.zmn.oms.zmn.business.impl.work.masterwork;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.common.enums.ChannelLevelEnum;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.common.data.common.dro.tags.TagsDRO;
import com.zmn.base.common.data.dubbo.interfaces.tags.TagsListRemoteService;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.conf.attachment.ConfOrderAttachmentBService;
import com.zmn.oms.business.interfaces.messageV1.common.MessageGetSendInfoService;
import com.zmn.oms.business.interfaces.orderamount.OrderAmountBService;
import com.zmn.oms.business.interfaces.orderfinalpricequotation.OrderFinalPriceQuotationBService;
import com.zmn.oms.business.interfaces.part.OrderPartBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.common.constant.DiscountConsts;
import com.zmn.oms.common.constant.OmsErrorCodeConsts;
import com.zmn.oms.common.constant.OrderAttachmentTypeEnum;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dio.quotation3.ArtificialPromDRO;
import com.zmn.oms.common.dro.finalpricequotation.OrderFinalPriceQuotationDRO;
import com.zmn.oms.common.dro.quotation3.Quotation3WorkDetailDRO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.work.modify.ArtificialPromQueryDTO;
import com.zmn.oms.model.entity.conf.attachment.ConfOrderAttachment;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.order.OrderFinalPrice;
import com.zmn.oms.model.entity.orderappbind.OrderThirdAppBind;
import com.zmn.oms.model.entity.orderattachment.OrderAttachmentQuery;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.quotation3.OrderFaultPhenomenon;
import com.zmn.oms.model.entity.quotation3.OrderQuotationProcess;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.OperatePermissionVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.order.OrderFinalPriceService;
import com.zmn.oms.services.interfaces.orderencrypt.OrderEncryptService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.quotation3.OrderFaultPhenomenonService;
import com.zmn.oms.services.interfaces.quotation3.OrderQuotationProcessService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.oms.zmn.business.interfaces.work.masterwork.MasterWorkListBService;
import com.zmn.oms.zmn.normal.business.impl.part.ZsNormalOrderPartBServiceImpl;
import com.zmn.uuc.dubbo.interfaces.user.UserThirdListRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author sunlife
 * @date:2022/1/7 3:02 下午
 * description:
 */
@Slf4j
@Service
public class MasterWorkListBServiceImpl implements MasterWorkListBService {

    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderProductService orderProductService;
    @Autowired
    OrderExtendService orderExtendService;
    @Autowired
    ConfOrderAttachmentBService confOrderAttachmentBService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderEncryptService orderEncryptService;
    @Autowired
    OrderQuotationProcessService orderQuotationProcessService;
    @Autowired
    OrderFinalPriceService orderFinalPriceService;
    @Autowired
    OrderPartBService orderPartBService;
    @Autowired
    ZsNormalOrderPartBServiceImpl zsNormalOrderPartBService;
    @Autowired
    OrderAmountBService orderAmountBService;
    @Autowired
    private MessageGetSendInfoService messageGetSendInfoService;
    @Autowired
    ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;
    @Autowired
    private ServItemBService servItemBService;
    @Autowired
    private OrderDiscountService orderDiscountService;

    @Resource
    private OrderFaultPhenomenonService orderFaultPhenomenonService;

    @Resource
    private OrderFinalPriceQuotationBService orderFinalPriceQuotationBService;

    @Resource
    private OrderServiceItemService orderServiceItemService;

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    ChannelListRemoteService channelListRemoteService;
    @DubboReference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION,check = false)
    private UserThirdListRemoteService userThirdListRemoteService;

    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private TagsListRemoteService tagsListRemoteService;

    @NacosValue(value = "${service.order.process.tagId:14033}", autoRefreshed = true)
    private Integer serviceOrderProcessTagId;

    @Override
    public Quotation3WorkDetailDRO getQuotation3WorkDetail(Long orderId, Long workId) throws OmsBaseException {
        Quotation3WorkDetailDRO workDetailDRO = new Quotation3WorkDetailDRO();

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (orderWork == null) {
            throw new OmsBaseException(OmsErrorCodeConsts.ORDER_NOT_FOUND, "订单不存在");
        }
        workDetailDRO.setOrderId(orderWork.getOrderId());
        workDetailDRO.setWorkId(orderWork.getWorkId());
        workDetailDRO.setBizType(orderWork.getBizType());
        workDetailDRO.setCategId(orderWork.getCategId());
        workDetailDRO.setChannelId(orderWork.getChannelId());
        workDetailDRO.setCityId(orderWork.getCityId());
        workDetailDRO.setMember(orderWork.getMember());
        workDetailDRO.setServCategId(orderWork.getServCategId());
        workDetailDRO.setCategOneId(orderWork.getCategOneId());
        workDetailDRO.setServItemType(orderWork.getServItemType());
        workDetailDRO.setFinalPrice(orderWork.getFinalPrice());
        workDetailDRO.setVipChannel(this.getVipChannelFlag(orderWork.getChannelId()));

        // 是否扫码用户
        OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderId);
        Boolean scanCode = NumberUtil.isNotNullOrZero(orderWork.getVisitUserId());
        if (Objects.nonNull(orderExtend) && NumberUtil.isNotNullOrZero(orderExtend.getWeChatScanUserId())) {
            orderWork.setVisitUserId(orderExtend.getWeChatScanUserId());
            scanCode = true;
        }

        if (scanCode){
            // 用户扫码了 判断是否关注公众号
            scanCode = checkAttentionWeChat(orderWork);
        }
        workDetailDRO.setScanCode(scanCode);

        OrderProduct product = orderProductService.listOrderProductByOrderId(orderId).get(0);
        workDetailDRO.setTariffId(product.getTariffId());
        workDetailDRO.setBrandId(product.getBrandId());
        workDetailDRO.setBrandName(product.getBrandName());
        workDetailDRO.setProductId(product.getProductId());
        workDetailDRO.setProductName(product.getProductName());
        workDetailDRO.setShowProductId(product.getShowProductId());
        workDetailDRO.setShowProductName(product.getShowProductName());
        workDetailDRO.setCategOneName(product.getCategOneName());

        OrderAttachmentQuery query = new OrderAttachmentQuery();
        query.setOrderId(orderWork.getOrderId());
        query.setWorkId(orderWork.getWorkId());
        query.setChannelId(orderWork.getChannelId());
        query.setBizType(orderWork.getBizType());
        query.setType(OrderAttachmentTypeEnum.CONSTS_ZBZ);
        query.setServCategId(orderWork.getServCategId());
        query.setCityId(orderWork.getCityId());
        query.setProductId(orderWork.getShowProductId());
        query.setBizLine(orderWork.getBizLine());

        // 获取装备照的配置
        ConfOrderAttachment equipmentPhotoConfig = confOrderAttachmentBService.getAttachmentConfigByQuery(query);
        if (Objects.nonNull(equipmentPhotoConfig)) {
            workDetailDRO.setNeedUploadEquipmentPicture(GlobalConsts.YES);
        }

        // 订单详情
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);
        workDetailDRO.setTelephone(StringUtil.formatHideMobile(orderDetail.getTelephone()));
        workDetailDRO.setCityName(orderDetail.getCityName());

        OrderQuotationProcess process = orderQuotationProcessService.findByOrderId(orderId);
        workDetailDRO.setCheckType(GlobalConsts.NONE);
        workDetailDRO.setCheckFaultCodeStatus(GlobalConsts.NO);
        if (Objects.nonNull(process)) {
            workDetailDRO.setCheckType(Optional.ofNullable(process.getCheckType()).orElse(GlobalConsts.NONE));
            workDetailDRO.setCheckFaultCodeStatus(process.getCheckFaultCodeStatus());
        }

        // 一口价下单数据
        OrderFinalPrice finalPriceOrderExt = orderFinalPriceService.findByOrderIdAndWorkId(orderId, workId);
        if (Objects.nonNull(finalPriceOrderExt)) {
            workDetailDRO.setPaceanOrderPayType(finalPriceOrderExt.getPayType());
            workDetailDRO.setPaceanOrderItemTypeName(finalPriceOrderExt.getItemTypeName());
        }
        if (Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)) {
            workDetailDRO.setPartUseType(zsNormalOrderPartBService.getPartUseType(orderWork));
        }

        // 一口价订单和服务订单处理
        if (Objects.equals(orderWork.getFinalPrice(),GlobalConsts.YES) ||
                Objects.equals(orderWork.getServItemType(),OrderConsts.SERVICE_ITEM_TYPE_ORDER)){

            OrderFinalPriceQuotationDRO orderFinalPriceQuotation = orderFinalPriceQuotationBService.
                    getOrderFinalPriceQuotationByOrderIdAndWorkId(orderId, workId);

            // 是否走默认服务流程
            if (Objects.equals(orderWork.getServItemType(),OrderConsts.SERVICE_ITEM_TYPE_ORDER)){
                ResponseDTO<TagsDRO> responseDTO = tagsListRemoteService.getById(serviceOrderProcessTagId);
                if (responseDTO.isSuccess()){
                    TagsDRO tagsDRO = responseDTO.getData();
                    if (Objects.nonNull(tagsDRO) && Objects.equals(tagsDRO.getStatus(),GlobalConsts.YES) &&
                            NumberUtil.isNotNullOrZero(orderWork.getProductId())){
                        workDetailDRO.setServiceOrderProcess(GlobalConsts.YES);
                    }
                }
            }
            if (Objects.nonNull(orderFinalPriceQuotation)){
                // 产品名称
                if (!Objects.equals(orderFinalPriceQuotation.getProductId(),orderWork.getProductId())){
                    workDetailDRO.setOldProductId(orderFinalPriceQuotation.getProductId());
                    workDetailDRO.setOldProductName(orderFinalPriceQuotation.getProductName());
                }

                // 品牌
                if (!Objects.equals(orderFinalPriceQuotation.getBrandId(),product.getBrandId())){
                    workDetailDRO.setOldBrandId(orderFinalPriceQuotation.getBrandId());
                    workDetailDRO.setOldBrandName(orderFinalPriceQuotation.getBrandName());
                }

                // 故障现象
                List<OrderFaultPhenomenon> orderFaultPhenomena = orderFaultPhenomenonService.listByOrderId(orderId);
                if (CollectionUtil.isNotNullOrEmpty(orderFaultPhenomena)){
                    OrderFaultPhenomenon orderFaultPhenomenon = orderFaultPhenomena.get(0);
                    workDetailDRO.setPhenId(orderFaultPhenomenon.getPhenId());
                    workDetailDRO.setPhenName(orderFaultPhenomenon.getPhenName());
                    if (!Objects.equals(orderFinalPriceQuotation.getPhenId(),orderFaultPhenomenon.getPhenId())){
                        workDetailDRO.setOldPhenId(orderFinalPriceQuotation.getPhenId());
                        workDetailDRO.setPhenName(orderFinalPriceQuotation.getPhenName());
                    }
                }else {
                    workDetailDRO.setOldPhenId(orderFinalPriceQuotation.getPhenId());
                    workDetailDRO.setPhenName(orderFinalPriceQuotation.getPhenName());
                }

                // 服务项目
                List<OrderServiceItem> orderServiceItems = orderServiceItemService.listByOrderId(orderId);
                if (CollectionUtil.isNotNullOrEmpty(orderServiceItems)){
                    OrderServiceItem orderServiceItem = orderServiceItems.get(0);
                    workDetailDRO.setServItemId(orderServiceItem.getServItemId());
                    workDetailDRO.setServItemName(orderServiceItem.getServItemName());
                    if (!Objects.equals(orderFinalPriceQuotation.getServItemId(),orderServiceItem.getServItemId())){
                        workDetailDRO.setOldServItemId(orderFinalPriceQuotation.getServItemId());
                        workDetailDRO.setOldServItemName(orderFinalPriceQuotation.getServItemName());
                    }
                }

                // 应付价格
                workDetailDRO.setTotalAmount(orderWork.getTotalAmount());
                workDetailDRO.setOldTotalAmount(orderFinalPriceQuotation.getTotalAmount());

            }
        }

        // 剩余应收金额
//        workDetailDRO.setRemainingReceivableAmount(orderAmountBService.getOrderWorkRemainingReceivableAmount(orderWork));
        this.setWorkDetailDiscountFlag(workDetailDRO,orderWork);
        return workDetailDRO;
    }

    private void setWorkDetailDiscountFlag(Quotation3WorkDetailDRO workDetailDRO,OrderWork orderWork) throws OmsBaseException {
        Long orderId = workDetailDRO.getOrderId();
        Long workId = workDetailDRO.getWorkId();

        OperatePermissionVO permissionDiscount = orderWorkOperatePermissionBService.getOperatePermission(workDetailDRO.getOrderId(), workDetailDRO.getWorkId(), OrderConsts.ORDER_OP_TYPE_DISCOUNT_LEVEL_ONE);
        log.debug("workId={} 优惠标志 出参：{}", workDetailDRO.getWorkId(), JSON.toJSONString(permissionDiscount));
        workDetailDRO.setDiscountFlag(GlobalConsts.NO);
        if (!permissionDiscount.getCanOperate()) {
            return;
        }
        // 3.0和一口价 判断用户是否同意维修展示优惠入口
        OrderQuotationProcess orderQuotationProcess = orderQuotationProcessService.findByOrderIdSrcMaster(orderId);
        if (Objects.nonNull(orderQuotationProcess) && Objects.equals(orderQuotationProcess.getAgreeStatus(),GlobalConsts.NO)){
            return;
        }
        // 一口价
        if (Objects.equals(workDetailDRO.getFinalPrice(), GlobalConsts.YES)) {

            // 没有尾款 不申请优惠
            if (NumberUtil.isNullOrZero(orderWork.getMasterAmount()) || orderWork.getMasterAmount() < 0) {
                return;
            }
            ArtificialPromQueryDTO artificialPromQueryDTO = ArtificialPromQueryDTO.builder().bizType(workDetailDRO.getBizType()).channelId(workDetailDRO.getChannelId()).cityId(workDetailDRO.getCityId()).orderExtendedWarranty(workDetailDRO.getMember()).plat(orderWork.getPlatWork()).productId(workDetailDRO.getShowProductId()).partUse(orderWork.getPartUse()).originalAmount(orderWork.getOriginalAmount()).usedDiscountAmount(orderWork.getDiscountAmount()).orderId(orderId).workId(workId).build();
            List<ArtificialPromDRO> artificialPromDROList = servItemBService.listArtificialProm(OrderConsts.SERVICE_ITEM_TYPE_FINAL_PRICE, artificialPromQueryDTO);
            if (CollectionUtil.isNotNullOrEmpty(artificialPromDROList)) {
                workDetailDRO.setDiscountFlag(GlobalConsts.YES);
            }else {
                // 获取人工优惠金额
                List<OrderDiscount> discounts = orderDiscountService.listByOrderIdSrcMaster(orderId);
                Integer artificialDiscountAmount = discounts.stream().filter(discount -> Objects.equals(discount.getCateg(), DiscountConsts.DISCOUNT_CATEG_ARTIFICIAL)).mapToInt(OrderDiscount::getAmount).sum();
                if (artificialDiscountAmount > 0){
                    // 有人工优惠的情况下 可以进入人工优惠页面
                    workDetailDRO.setDiscountFlag(GlobalConsts.YES);
                }
            }
            return;

        } else {
            ArtificialPromQueryDTO artificialPromQueryDTO = ArtificialPromQueryDTO.builder().bizType(workDetailDRO.getBizType()).channelId(workDetailDRO.getChannelId()).cityId(workDetailDRO.getCityId()).orderExtendedWarranty(workDetailDRO.getMember()).plat(orderWork.getPlatWork()).productId(workDetailDRO.getShowProductId()).build();
            List<ArtificialPromDRO> artificialPromDROList = servItemBService.listArtificialProm(OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE, artificialPromQueryDTO);
            if (CollectionUtil.isNotNullOrEmpty(artificialPromDROList)) {
                workDetailDRO.setDiscountFlag(GlobalConsts.YES);
            }
        }
    }

    // 查询渠道vip标识
    private Integer getVipChannelFlag(Integer channelId) {
        ResponseDTO<ChannelDRO> channelRespDTO = channelListRemoteService.getByChannelId(channelId);
        if (channelRespDTO.isSuccess() && channelRespDTO.getData() != null) {
            return Optional.ofNullable(channelRespDTO.getData().getLevel()).orElse(0) == ChannelLevelEnum.VIP.getCode() ? GlobalConsts.YES : GlobalConsts.NO;
        } else {
            return GlobalConsts.NONE;
        }
    }

    /**
     * 检验用户是否关注
     * @param orderWork 工单信息
     */
    private Boolean checkAttentionWeChat(OrderWork orderWork) throws OmsBaseException{
        OrderThirdAppBind orderThirdAppBind = messageGetSendInfoService.getOrderWeChatBindInfoForOrderBy(orderWork.getOrderId(), orderWork.getPlatWork());
        if (Objects.isNull(orderThirdAppBind) || StringUtils.isBlank(orderThirdAppBind.getThirdAppId())) {
            log.info("订单号{}，未找到绑定公众号信息", orderWork.getWorkId());
            return false;
        }

        ResponseDTO<Boolean> isAttentionWechat = userThirdListRemoteService.getThirdSubscribeByUserIdAndAppId(orderWork.getVisitUserId(), orderThirdAppBind.getThirdAppId());
        log.info("订单号{},查询用户是否关注公众号,userId:{},appId:{},出参:{}",orderWork.getOrderId(),orderWork.getVisitUserId(),orderThirdAppBind.getThirdAppId(),isAttentionWechat);
        if (isAttentionWechat.isSuccess() && Objects.nonNull(isAttentionWechat.getData())){
            return isAttentionWechat.getData();
        }else {
            log.error("调用getThirdSubscribeByUserIdAndAppId查看用户是否关注公众号接口错误");
            return false;
        }
    }
}
